from __future__ import annotations
from typing import Optional
from sqlalchemy.orm import Mapped, mapped_column, relationship
from extensions import db
from datetime import datetime
from sqlalchemy import func  # 新增导入

class UserStore(db.Model):
    """用户店铺关系模型"""
    __tablename__ = 'user_stores'

    # 添加自增长主键
    id: Mapped[int] = mapped_column(db.Integer, primary_key=True, autoincrement=True)
    # 用户ID
    user_id: Mapped[str] = mapped_column(db.String(36))
    # 店铺ID
    store_id: Mapped[str] = mapped_column(db.String(36))
    # 添加联合唯一约束
    __table_args__ = (db.UniqueConstraint('user_id', 'store_id', name='uix_user_store'),)

    # 用户在店铺中的角色，如：owner-店主，manager-店长，staff-员工, customer-客户等等
    role: Mapped[str] = mapped_column(db.String(20), nullable=False)
    # 用户折扣比例，默认为1表示无折扣
    discount_rate: Mapped[float] = mapped_column(db.Float, nullable=True, default=1.0)
    # 用户提成比例，默认为0.3表示30%提成
    commission_rate: Mapped[float] = mapped_column(db.Float, nullable=True, default=0.3)
    # 用户在店铺中的股份比例，存储为小数(0.01-1.00)，默认为0表示无股份
    equity_ratio: Mapped[float] = mapped_column(db.Float, nullable=True, default=0.0)
    # 记录创建时间
    created_at: Mapped[datetime] = mapped_column(
        db.DateTime,
        server_default=func.now(),  # 优先使用数据库当前时间
        default=datetime.utcnow     # 使用Python系统时间作为后备
    )
    # 记录最后更新时间
    updated_at: Mapped[datetime] = mapped_column(
        db.DateTime,
        server_default=func.now(),  # 优先使用数据库当前时间
        default=datetime.utcnow,    # 使用Python系统时间作为后备
        onupdate=datetime.utcnow    # 更新时使用Python系统时间
    )

    # 添加软删除标记
    is_deleted: Mapped[bool] = mapped_column(db.Boolean, default=False, nullable=False)

    def __init__(self, user_id: str, store_id: str, role: str, discount_rate: float = 1.0, 
                 commission_rate: float = 0.0, equity_ratio: float = 0.0) -> None:
        self.user_id = user_id
        self.store_id = store_id
        self.role = role
        self.discount_rate = discount_rate
        self.commission_rate = commission_rate
        self.equity_ratio = equity_ratio
        self.is_deleted = False  # 添加初始化值

    def to_dict(self) -> dict:
        """将模型转换为字典"""
        return {
            'id': self.id,
            'user_id': self.user_id,
            'store_id': self.store_id,
            'role': self.role,
            'discount_rate': self.discount_rate,
            'commission_rate': self.commission_rate,
            'equity_ratio': self.equity_ratio  if self.equity_ratio is not None else 0,  
            'created_at': self.created_at.isoformat() if self.created_at else None,
            'updated_at': self.updated_at.isoformat() if self.updated_at else None,
            'is_deleted': self.is_deleted
        }